<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
  import * as echarts from 'echarts';
  import axios from 'axios';
  import { fontSize } from '/@/utils/echartsRem';
  import { forEach } from 'min-dash';
  import zhan from '/@/assets/svg/zhan.svg';
  import { defHttp } from '/@/utils/http/axios';
  import { getMapZC, warnLevelCount, getLineLngLat } from '/@/api/sys/largeScreen/api-map';
  import { equipQueryEquipState } from '/@/api/remoteOverview/api-remoteOverview';
  import { tooltip } from 'leaflet';

  let chart,
    result,
    result1,
    ZCDATA
    // echartsZoom = 0.55,
    // mapCenter = ['108.8204775', '37.62816632'];
  export default {
    props: {
      className: {
        type: String,
        default: 'chart',
      },
      width: {
        type: String,
        default: '100%',
      },
      height: {
        type: String,
        default: '100%',
      },
      autoResize: {
        type: Boolean,
        default: true,
      },
      chartDataLine: {
        type: Object,
        // required: true,
      },
      Standing: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        chart: null,
        mapName: null,
        color: {
          YY: '#549AFB',
          CPY: '#A5D931',
          TRQ: '#F53B28',
        },
        showLabel:false,
        echartsZoom: 0.55,  // 地图缩放
        mapCenter: ['108.8204775', '37.62816632'],  // 地图中心点
      };
    },
    watch: {
      chartDataLine: {
        deep: true,
        handler(val) {
          const that = this;
          console.log(val, '传递过来的val值');
          if (this.Standing) {
            this.updataOptions(val, ZCDATA);
          } else {
            this.updataOptions(val);
          }
        },
      },
      Standing: {
        handler(val) {
          // 更新站场
          if (val) {
            this.updataOptions(this.chartDataLine, ZCDATA);
          } else {
            this.updataOptions(this.chartDataLine);
          }
        },
      },
    },
    mounted() {
      this.$nextTick(() => {
        this.initChart();
      });
    },
    beforeDestroy() {
      if (!chart) {
        return;
      }
      chart.dispose();
      chart = null;
    },
    methods: {
      async initChart() {
        chart = echarts.init(this.$el);
        console.log(this.chartDataLine, 'chartDataLine');
        let Data = await defHttp.get({
          url: getMapZC,
          params: { type: 'ZC,FS', locationRequired: true },
        });
        // 处理战场数据
        ZCDATA = Data;

        let Linedata = await defHttp.get({ url: getLineLngLat });

        this.updataOptions(Linedata, Data);

        // 添加地图缩放监听
        chart.on('georoam', this.handleGeoRoam);
      },

      handleGeoRoam(event) {
        const zoom = chart.getOption().geo[0].zoom;
        const center = chart.getOption().geo[0].center;
        this.echartsZoom = zoom;
        this.mapCenter = center;
        this.currentCenter = center;
        this.updateScatterLabels(zoom);
        this.syncGeoLayers(zoom, center);
        // this.updateLineLabels(zoom);
      },

      // 让散点图标签根据缩放显示或隐藏
      updateScatterLabels(zoom) {
        const that = this;
        const threshold = 0.8; // 设置缩放阈值
        const series = chart.getOption().series;
        series.forEach((s) => {
          if (s.type === 'scatter') {
            that.showLabel = zoom > threshold
            s.label.show = that.showLabel;

            s.data.forEach((dataItem) => {
              if (dataItem.label) {
                dataItem.label.show = that.showLabel;
              }
            });
          }
        });
        chart.setOption({ series });
      },

      // 让所有的geo跟随移动
      syncGeoLayers(zoom, center) {
        const option = chart.getOption();
        option.geo.forEach((geo, index) => {
          geo.zoom = zoom;
          geo.center = center;
        });
        chart.setOption(option);
      },

      updataOptions(Linedata, zcdata = []) {
        const that = this;
        let seriesData = [];
        // let graphicElements = [];
        let linesName = [];

        for (const key in Linedata) {
          if (Object.prototype.hasOwnProperty.call(Linedata, key)) {
            const item = Linedata[key];
            console.log(item, 'item');
            for (const o in item) {
              if (Object.prototype.hasOwnProperty.call(item, o)) {
                const element = item[o];

                element.forEach((i) => {
                  // 取i中间序号的值
                  const midIndex = Math.floor(i.length / 2);
                  // 计算标签的位置
                  const midPoint = i[midIndex];
                  linesName.push({
                    name: o,
                    value: midPoint,
                    label: {
                      show: that.showLabel, // 初始状态下不显示标签
                      position: 'right',
                      textStyle: {
                        color: that.color[key],
                        textBorderColor: '#000', // 描边颜色
                        textBorderWidth: 2, // 描边宽度
                        fontFamily: 'Microsoft YaHei',
                      },
                      formatter: function (res) {
                        return res.name;
                      },
                    },
                  });

                  // 地图画线 
                  seriesData.push({
                    type: 'lines',
                    zlevel: 2,
                    polyline: true,  // 多段线一定要加这个，不然显示不出来
                    coordinateSystem: 'geo', // 使用地理坐标系,默认为直角坐标系，通过 coordinateSystem 设置 也可以结合百度等
                    lineStyle: {
                      normal: {
                        color: that.color[key],
                        width: 2, //尾迹线条宽度
                        opacity: 1, //尾迹线条透明度
                      },
                    },
                    data: [{ coords: i, name: o }], //线由多个经纬度构成的时候  多段线的经纬度 应该写coords:[]
                  });
                });
              }
            }
          }
        }

        // 线添加label (因为polyline: true 时，线段加label时不显示的，因此换了一种方法，用线段上添加一个点，点的label来显示 )
        seriesData.push({
          type: 'scatter',
          coordinateSystem: 'geo',
          name: '站点',
          symbolSize: 0,
          opacity: 1,
          zlevel: 2,

          // 本来计划每条线的label显示是一样的格式，但是 不同线的颜色也不同，就把label的控制移动到了data中，根据颜色来显示label
          // label: {
          //   show: false, // 初始状态下不显示标签
          //   position: 'right',
          //   textStyle: {
          //     color: '#fff',
          //   },
          //   formatter: function (res) {
          //     return res.name;
          //   },
          // },

          // label散点是不显示tootip的，关掉就不显示了
          tooltip: {
            show: false,
          },
          data: linesName,
        });

        let latLng = zcdata.map((item) => {
          return {
            name: item.name,
            id: item.id,
            warnData: item.warnData,
            equipInfo: item.equipInfo,
            value: [item.longitude, item.latitude, 0],
          };
        });
        // 画散点
        seriesData.push({
          type: 'scatter',
          coordinateSystem: 'geo',
          name: '站点',
          symbol: 'image://' + zhan,  // 自定义symbol  图片要加上image://
          symbolSize: 20,
          opacity: 1,
          zlevel: 2,
          label: {
            show: that.showLabel, // 初始状态下不显示标签
            position: 'top',
            textStyle: {
              color: '#1868de',
              textBorderColor: '#fff', // 描边颜色  //给文字加上描边
              textBorderWidth: 2, // 描边宽度
              fontFamily: 'Microsoft YaHei',
            },
            formatter: function (res) {
              return res.name;
            },
          },
          data: latLng,
        });

        this.setOptions(seriesData);
      },

      setOptions(seriesData) {
        const that = this;
        var province = '/config/provincesdata.json';  //加载地图数据
        axios.get(province).then((response) => {
          // 注册自定义的地图数据
          echarts.registerMap('province', response.data);

          let data = response.data.features.map((element, index) => {
            const name = element.properties.name;
            return {
              name,
            };
          });

          this.mapName = data;

          let option = {
            // 只有这个打开了，地图上的item tootip才能显示出来
            tooltip: {
              trigger: 'item',
              className: 'gdpViewPopup',  // 自定义样式
              formatter: function (params) {
                console.log(params, 'params');
                if (params.seriesType === 'scatter') {
                  return `
                   <div class="pannelContainer">
        <div class="title" id="pannel_map_title">${params.name}</div>
        <div class="pannel_content">
            <div class="pannel_top">
                <div class="left">
                    <div class="normal">实时告警</div>
                    <div class="yellow" id="TOTAL">${params.data.warnData?.TOTAL || 0}</div>
                </div>
                <div class="center">
                    <div class="red warn-level">
                        <div>紧急</div>
                        <span id="URGENT">${params.data.warnData?.URGENT || 0}</span>
                    </div>
                    <div class="orange warn-level">
                        <div>重要</div>
                        <span id="IMPORTANT">${params.data.warnData?.IMPORTANT || 0}</span>
                    </div>
                    <div class="green warn-level">
                        <div>一般</div>
                        <span id="COMMON">${params.data.warnData?.COMMON || 0}</span>
                    </div>
                    <div class="blue warn-level">
                        <div>普通</div>
                        <span id="GENERAL">${params.data.warnData?.GENERAL || 0}</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
                  `;

                  // return `站点名称: ${params.name}<br/>
                  // 实时告警: ${params.data.warnData?.TOTAL || 0}<br/>
                  // 紧急: ${params.data.warnData?.URGENT || 0}<br/>
                  // 重要: ${params.data.warnData?.IMPORTANT || 0}<br/>
                  // 一般: ${params.data.warnData?.COMMON || 0}<br/>
                  // 普通: ${params.data.warnData?.GENERAL || 0}<br/>
                  // `;
                } else if (params.seriesType === 'lines') {
                  return `线路名称: ${params.data.name}`;
                }
                return '';
              },
            },
            // geo 是用来承载在地图上的线、点的 目前是有2个
            geo: [
              {
                map: 'province',
                aspectScale: 1,
                zoom: this.echartsZoom,
                layoutCenter: ['53%', '45%'], // 地图在页面上的展示的位置
                center: this.mapCenter, //地图视角的中心点位
                layoutSize: '180%',
                show: true,
                roam: true,
                animationDurationUpdate: 0,  //防止拖动卡顿
                tooltip: {
                  show: true,
                },
                label: {
                  // emphasis: {
                  //   show: false,
                  // },
                },
                itemStyle: {
                  normal: {
                    areaColor: {
                      type: 'linear',
                      x: 2000,
                      y: 0,
                      x2: 0,
                      y2: 0,
                      colorStops: [
                        {
                          offset: 0,
                          color: 'rgba(6, 26, 68,0.9)', // 0% 处的颜色
                        },
                        {
                          offset: 1,
                          color: 'rgba(57, 148, 251,0.9)', // 50% 处的颜色
                        },
                      ],
                      global: true, // 缺省为 false
                    },
                    borderColor: '#fff',
                    borderWidth: 0.2,
                  },
                },
                // 禁止高亮使用的是 disabled 不是show
                emphasis: {
                  disabled: true,
                },
              },
              {
                map: 'province',
                aspectScale: 1,
                zoom: this.echartsZoom,
                layoutCenter: ['53%', '45%'],
                layoutSize: '180%',
                center: this.mapCenter,
                show: true,
                roam: true,
                animationDurationUpdate: 0,
                zlevel: -1,
                tooltip: {
                  show: true,
                },
                label: {
                  // emphasis: {
                  //   show: false,
                  // },
                },
                itemStyle: {
                  normal: {
                    borderWidth: 5,
                    borderColor: 'rgba(65, 214, 255,1)',
                    shadowColor: 'rgba(65, 214, 255,0.6)',
                    shadowOffsetY: 5,
                    shadowBlur: 15,
                    areaColor: 'rgba(5,21,35,0.1)',
                  },
                },
                emphasis: {
                  disabled: true,
                },
              },
            ],
            series: [...seriesData],
          };
          chart.setOption(option, true);
        });
      },
    },
  };
</script>
